<script setup lang="ts">
import { onMounted, ref } from 'vue'
import { useRoute } from 'vue-router'
import { useProductStore } from '@/stores/product'
import { useCartStore } from '@/stores/cart'

const route = useRoute()
const product = useProductStore()
const cart = useCartStore()
const count = ref(1)

onMounted(async () => {
  const id = Number(route.params.id)
  await product.fetchDetail(id)
})

function add() {
  if (!product.detail) return
  cart.add(product.detail, product.detail.skus?.[0] || null, count.value)
}
</script>

<template>
  <div class="container" v-if="product.detail">
    <div class="wrap">
      <div class="media">
        <img :src="product.detail.picUrl || product.detail.sliderPicUrls?.[0]" alt="" />
      </div>
      <div class="info">
        <h1 class="name">{{ product.detail.name }}</h1>
        <div class="price">￥{{ (product.detail.price || product.detail.skus?.[0]?.price || 0).toFixed(2) }}</div>
        <p class="desc">{{ product.detail.introduction }}</p>
        <div class="actions">
          <input type="number" v-model.number="count" min="1" />
          <button @click="add">加入购物车</button>
        </div>
      </div>
    </div>
    <div class="content" v-if="product.detail.description">
      <h3>详情</h3>
      <div v-html="product.detail.description"></div>
    </div>
  </div>
</template>

<style scoped>
.wrap { display: grid; grid-template-columns: 420px 1fr; gap: 24px; padding: 16px; }
.media img { width: 100%; height: 320px; object-fit: cover; background: #fafafa; border: 1px solid #eee; border-radius: 8px; }
.name { margin: 0; font-size: 20px; }
.price { color: #e22; font-size: 20px; margin: 12px 0; }
.actions { display: flex; gap: 8px; }
.actions input { width: 80px; padding: 8px; border: 1px solid #ddd; border-radius: 4px; }
.actions button { padding: 8px 12px; border: 1px solid #ddd; border-radius: 4px; background: #42b883; color: #fff; }
.content { padding: 16px; }
</style>